# coding=utf-8
"""

"""

from flask import request
from base.base_res import res_success, res_base
from . import bp
from services.users import *
from utils.token_util import generate_token, refresh_access_token


# @Time    :  2024-10-18 09:23:15
# @Author  :  jiangtong
# @Email   :  gingerqgyy@outlook.com
# @Project :  ginger_yl_test_boost
# @File    :  users


# 查询用户列表 :
@bp.route('/list', methods=['GET'])
def user_list():
    _users = list_user()
    _users_res = [{'account': item.get('account'), 'avatar': item.get('avatar')} for item in _users]
    return res_success(result=_users_res)


# 用户登录 :
@bp.route('/login', methods=['POST'])
def login():
    _param = request.get_json()
    account = _param.get('account')
    pwd = _param.get('password')
    _res = login_user(account, pwd)
    # 登录成功, 需要生成 token, 添加到响应头中 :
    if _res[0]:
        _access_token, _refresh_token = generate_token(username=account)
        return res_base(message=_res[-1], result={'access_token': _access_token, 'refresh_token': _refresh_token})
    return res_base(message=_res[-1])


# 刷新 token :
@bp.route('/refresh_token', methods=['get'])
def refresh_token():
    is_success, res_data = refresh_access_token()
    if not is_success:
        return res_base(*res_data)
    return res_base(result={'access_token': res_data})
